package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RedisData;
import com.hmdp.utils.SystemConstants;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Object queryById(Long id) {
        String shopKey = CACHE_SHOP_KEY + id;
        // 从redis查询商店缓存
        String shopJson = stringRedisTemplate.opsForValue().get(shopKey);
        // 判断缓存是否存在
        if (StrUtil.isNotBlank(shopJson)) {
            // 缓存存在，直接返回
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return Result.ok(shop);
        }
        // 判断命中的是否是空值
        if (shopJson != null) {
            // 命中空值，直接返回
            return Result.fail("商铺不存在");
        }
        // 缓存不存在，查询数据库
        Shop shop = getById(id);
        // 店铺不存在, 返回错误
        if (shop == null) {
            // 将空值写入redis
            stringRedisTemplate.opsForValue().set(shopKey, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
            // 返回错误信息
            return Result.fail("商铺不存在");
        }
        // 店铺存在, 写入redus
        stringRedisTemplate.opsForValue().set(shopKey, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);
        // 返回
        return Result.ok(shop);
    }

    @Override
    @Transactional
    public Result updateShop(Shop shop) {
        Long id = shop.getId();
        if (id == null) {
            return Result.fail("商铺ID不能为空");
        }
        // 更新数据库
        updateById(shop);
        // 删除缓存
        stringRedisTemplate.delete(CACHE_SHOP_KEY + id);
        return Result.ok();
    }


    // 缓存击穿
    public Shop queryWithMutex(Long id){
        String shopKey = CACHE_SHOP_KEY + id;
        // 从redis查询商店缓存
        String shopJson = stringRedisTemplate.opsForValue().get(shopKey);
        // 判断缓存是否存在
        if(StrUtil.isNotBlank(shopJson)){
            // 缓存存在，直接返回
            return JSONUtil.toBean(shopJson, Shop.class);
        }
        // 判断命中的是否是空值
        if(shopJson != null){
            // 命中空值，直接返回
            return null;
        }
        // 实现缓存重建
        // 1. 获取互斥锁
        String lockKey = "lock:shop:" + id;
        Shop shop = null;
        try{
            boolean isLock = tryLock(lockKey);
            // 2. 判断是否获取成功
            if(!isLock){
                // 3. 失败 则休眠并重试
                Thread.sleep(50);
                return queryWithMutex(id);
            }
            // 4. 成功 根据id查询数据库
            shop = getById(id);
            // 模拟重建延时
            Thread.sleep(1000);
            // 店铺不存在, 返回错误
            if(shop == null){
                // 将空值写入redis
                stringRedisTemplate.opsForValue().set(shopKey, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
                // 返回错误信息
                return null;
            }
            // 店铺存在, 写入redus
            stringRedisTemplate.opsForValue().set(shopKey, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);
        }catch(InterruptedException e){
            throw new RuntimeException(e);
        }finally{
            // 释放互斥锁
            unLock(lockKey);
        }
        // 返回
        return shop;
    }

    // 获取锁
    private boolean tryLock(String key){
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }
    // 释放锁
    private void unLock(String key){
        stringRedisTemplate.delete(key);
    }



    // 数据预热 / 缓存重建
    public void saveShopRedis(Long id, Long expireSeconds){
        // 1. 查询店铺数据
        Shop shop = getById(id);
        // 2. 封装逻辑过期时间
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
        // 3. 写入Redis
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(redisData));
    }

    // 独立线程重建缓存(线程池)
    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);
    // 逻辑过期解决缓存击穿
    public Shop queryWithLogicalExpire(Long id){
        String shopKey = CACHE_SHOP_KEY + id;
        // 1. 从redis查询商店缓存
        String shopJson = stringRedisTemplate.opsForValue().get(shopKey);
        // 2. 判断缓存是否存在
        if(StrUtil.isBlank(shopJson)){
            // 3. 缓存不存在，直接返回
            return null;
        }
        // 4. 命中, 需要先把json反序列化为对象
        RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
        Shop shop = JSONUtil.toBean((JSONObject) redisData.getData(), Shop.class);
        LocalDateTime expireTime = redisData.getExpireTime();
        // 5. 判断是否过期
        if(expireTime.isAfter(LocalDateTime.now())){
            // 5.1 未过期, 直接返回
            return shop;
        }
        // 5.2 过期, 重建缓存
        // 6. 缓存重建
        // 6.1 获取互斥锁
        String lockKey = LOCK_SHOP_KEY + id;
        boolean isLock = tryLock(lockKey);
        // 6.2 判断是否获取成功
        if(isLock){
            // 6.3 成功, 开启独立线程, 实现缓存重建
            CACHE_REBUILD_EXECUTOR.submit(() -> {
                try {
                    // 重建缓存
                    this.saveShopRedis(id, 20L);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    // 释放互斥锁
                    unLock(lockKey);
                }
            });
        }
        // 6.4 返回过期的商铺信息
        return shop;
    }

    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        //1.判断是否需要根据坐标进行查询
        if(x==null||y==null){
            Page<Shop> page = query().eq("type_id", typeId).page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            return Result.ok(page.getRecords());
        }
        //2.计算分页参数
        int from = (current-1)*SystemConstants.DEFAULT_PAGE_SIZE;
        int end = current * SystemConstants.DEFAULT_PAGE_SIZE;
        //3.查询redis,按照距离排序，分页  geosearch bylonlat x y byredius 10 (km/m) withdistance
        String typeKey = SHOP_GEO_KEY + typeId;
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo()
                .search(
                        typeKey,
                        GeoReference.fromCoordinate(x, y),
                        new Distance(5000),
                        RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance().limit(end)//只能从0到end,后面需要自己截取
                );
        //4.解析出id
        if(results==null){
            return Result.ok(Collections.emptyList());
        }
        //4.1我们要的地方的list集合(店铺Id+distance)
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> content = results.getContent();
        //有可能等下skip把数据都跳过了，所以需要判空
        if(content.size()<=from){
            //没有下一页
            return Result.ok(Collections.emptyList());
        }
        //4.2.截取first-end
        List<Long> ids = new ArrayList<>(content.size());
        Map<String,Distance> distMap = new HashMap<>(content.size());
        content.stream().skip(from).forEach(result ->{
            //4.2.1获取店铺Id
            String shopIdStr = result.getContent().getName();
            ids.add(Long.valueOf(shopIdStr));
            //4.2.2获取距离
            Distance distance = result.getDistance();

            distMap.put(shopIdStr,distance);
        });//这里其实就是通过stream流将shopId提取出来，并且要根据距离进行排序

        //5.根据id查询shop
        String idStr = StrUtil.join(",",ids);//1,2,3,4...
        // .... where id in #{ids} order by field(id,1,2,3,4...) 根据id排序
        List<Shop> shops = query().in("id", ids).last("order by field(id," + idStr + ")").list();

        for (Shop shop : shops) {
            shop.setDistance(distMap.get(shop.getId().toString()).getValue());
        }
        return Result.ok(shops);
    }







}

